package com.wy2.eclipse.tool.ui.handlers;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.jobs.IJobChangeEvent;
import org.eclipse.core.runtime.jobs.JobChangeAdapter;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.handlers.HandlerUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.wy2.core.date.DateTime;
import com.wy2.core.tool.StringTools;
import com.wy2.eclipse.tool.lib.git.CommitRun;
import com.wy2.eclipse.tool.lib.git.GitClient;
import com.wy2.eclipse.tool.lib.git.GitElementList;
import com.wy2.eclipse.tool.lib.git.GitJob;
import com.wy2.eclipse.tool.lib.git.GitRun;
import com.wy2.eclipse.tool.lib.git.PushRun;
import com.wy2.eclipse.tool.lib.git.addRun;
import com.wy2.eclipse.tool.ui.UIActivator;
import com.wy2.eclipse.tool.ui.preferences.PreferenceConstants;

public class CommitDataHandler extends AbstractHandler {
    
    private static final Logger logger=LoggerFactory.getLogger(CommitDataHandler.class);

    @Override
    public Object execute(ExecutionEvent event) throws ExecutionException {
        Boolean ok=MessageDialog.openConfirm(Display.getDefault().getActiveShell(), "提示", "确定要提交数据么？");
        if(!ok) {
            return null;
        }
        
        IPreferenceStore store = UIActivator.getDefault().getPreferenceStore();
        String user=store.getString(PreferenceConstants.P_GIT_USER);
        String password=store.getString(PreferenceConstants.P_GIT_PASSWOR);
        if(StringTools.isEmpty(user) || StringTools.isEmpty(password)) {
            logger.info("没有配置git用户名、密码");
            return null;
        }
        
        IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event);        
        final GitClient gitClient = UIActivator.getDefault().getGitClient();        
        GitElementList waitCommits =gitClient.getWaitCommit();
        
        if(waitCommits==null || waitCommits.isEmpty()) {
            logger.info("没有需要提交的数据...");
            return null;
        }
        
        List<GitRun> gitRuns=new ArrayList<>();
        
        if(waitCommits!=null && !waitCommits.isEmpty()) {
            gitRuns.add(new addRun(waitCommits.getPaths()));
        }        
        
        String[] commits=waitCommits.getPaths();
        if(commits!=null && commits.length>0) {
            gitRuns.add(new CommitRun(MessageFormat.format("auto commit By {0}", DateTime.Now().toString()),commits));
        }else {
            gitRuns.add(new CommitRun(MessageFormat.format("auto commit By {0}", DateTime.Now().toString()),null));
        }
        
        
        gitRuns.add(new PushRun(null,user,password,false));
        
        GitJob gitJob=new GitJob("新增、提交、推送文件", gitClient, gitRuns);
        gitJob.addJobChangeListener(new JobChangeAdapter() {
            @Override
            public void done(IJobChangeEvent event) {
              final IStatus result = event.getResult();
              final GitJob job=(GitJob) event.getJob();
              if(result.isOK()) {
                  logger.info("{} 成功",job.getName());
                  Display.getDefault().syncExec(new Runnable() {
                    @Override
                    public void run() {
                        logger.info("提交文件数量： {}",waitCommits.size());
                        
                        logger.info("提交文件列表：\n{}",waitCommits.getPrettyString());
                        MessageDialog.openInformation(Display.getDefault().getActiveShell(), "提示", "数据提交成功！~");                        
                    }
                });
                 
              }else if(IStatus.ERROR==result.getSeverity()) {
                  logger.error(job.getName()+"异常",result.getException());
                  Display.getDefault().syncExec(new Runnable() {
                      
                      @Override
                      public void run() {
                          MessageDialog.openError(Display.getDefault().getActiveShell(), "操作异常", "数据提交失败！~");
                      }
                  });
              }
              
            }
        });
        gitJob.schedule();
        return null;
    }

}
